package top.zhangjianyong.tools.timer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.zhangjianyong.tools.annotation.DoTimer;
import top.zhangjianyong.tools.entity.Holiday;
import top.zhangjianyong.tools.service.mybatis.IHolidayService;
import top.zhangjianyong.tools.utils.HolidayUtil;

import java.time.LocalDate;
import java.util.List;


@Slf4j
@Component
public class HolidayTimer {

    @Autowired
    private IHolidayService iHolidayService;
    @Autowired
    private HolidayUtil holidayUtil;

    @Value("${timer-flag}")
    private Boolean timerFlag;


    @Scheduled(cron = "0 0 1 1 1 ?")
    @DoTimer
    public void updateHoliday() {

        log.info("更新holiday数据开始");
        int year = LocalDate.now().getYear();
        log.info("获取当前年份：" + year);

        updateHoliday(year);
        log.info("更新holiday数据结束");
    }

    public void updateHoliday(int year) {
        List<Holiday> list = holidayUtil.HolidayListFromApi(year);
        list.forEach(holiday -> {
            Holiday one = iHolidayService.lambdaQuery()
                    .eq(Holiday::getDate, holiday.getDate())
                    .one();
            if (one == null) {
                iHolidayService.save(holiday);
            } else {
                BeanUtils.copyProperties(holiday, one);
                iHolidayService.updateById(one);
            }
        });
    }
}
